<template>
  <div>
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
        </el-row>


      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :multiple="false" :options="deptOptions" placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="cancel()">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import axios from "axios";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css"

export default {
  name: "Student12",
  components: {Treeselect},
  data() {
    return {
      // 非单个禁用
      single: true,
      open: false,
      title: "添加员工信息",
      form: {},
      userList:[],
      deptName: '',

      // 岗位数据
      postOptions:[],
      // 角色数据
      roleOptions:[],
      deptOptions:[],
      sexArrays: [
        {label: '男', value: 0},
        {label: '女', value: 1},
        {label: '未知', value: 2}
      ],
      arrayStatus: [
        {label: '正常', value: 0},
        {label: '停用', value: 1}
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 监听属性的变化
    deptName(val) {
      console.log("deptName", val);
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.deptTree();
    this.getInof()
  },

  methods: {
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            this.updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 属性结构从新命令
    transformTreeForFrontTend(treeData) {
      // 递归转换树形结构
      if (!treeData || typeof treeData !== "object") return null;
      // 遍历每个节点，创建新对象并重命字段
     return treeData.map(node =>{
       // 必选字段， id （原deptId）, label（原deptName）
       const newNode = {
         id: node.deptId,
         label: node.deptName
       };
       // 可选字段， children（子节点）,递归转换子节点
       if(node.children && Array.isArray(node.children)) {
         newNode.children = this.transformTreeForFrontTend(node.children);
       }
       return newNode;
     })
    },
    updateUser(row) {

      return axios.put("http://localhost:9090/sysUser/edit",this.form).then(res=>{

        const result = res.data.data
      })
    },
    addUser(row) {
      console.log("addUser", JSON.stringify(this.form))
      return  axios.post("http://localhost:9090/sysUser/add",this.form).then(res=>{
        const result = res.data.data
      })
    },
    handleDelete(){},
    handleUpdate(){},
    cancel() {
      this.open = false;
    },
    handleAdd() {
      this.open = true;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 查询用户列表 */
    getList() {

    },
    deptTree() {
      axios.get("http://localhost:9090/sysUser/deptTree").then(res=>{
        const result = res.data.data
        console.log("deptTree",JSON.stringify(result))
        this.deptOptions = this.transformTreeForFrontTend(result)
        console.log("deptOptions",this.deptOptions)
      })
    },
    getInof() {
      axios.get("http://localhost:9090/sysUser/getInfo").then(res=>{
        this.roleOptions = res.data.data.roles
        this.postOptions = res.data.data.posts
        console.log("getInof",this.roleOptions)
      })
    }
  }
};
</script>
